 var util = require('../../utils/util.js');
var wxcache = require('../../utils/wxcache.js');
var api = require('../../config/api.js');
var app = getApp()

Page({
  data: {
    keyword: '',
    searchStatus: true,
    historyKeyword: [],
    filterCategory: [],
    hotKeyword: [],
  },

  /**
   * 点击搜索
  */
  bindSearch: function () {
    this.searchByCondition();
  },
  /**
   * 清空输入框
  */
  clearKeyword: function () {
    this.setData({
      keyword: '',
      searchStatus: false
    });
  },

  onLoad: function (options) {

    // if (options.keyword){
    //   this.setData({
    //     keyword:options.keyword
    //   })
    // }

    this.getHotKeyword();

    var searchData = wxcache.get('searchData') || [];
    if (searchData.length>0){
      this.setData({
        historyKeyword: searchData,
        searchStatus: true
      });
    }
  },

  /**
   * 搜索
  */
  searchByCondition:function(){
    let that = this;
    //组织查询条件数据
    var param = {
      "campaignName": that.data.keyword || ""
    }
    util.request(api.ActivityUrl, param, 'GET').then(function (res) {

      var searchData = wxcache.get('searchData') || []

      var count = 0;
      for (var i = 0; i < searchData.length; i++) {
        if (searchData[i] == that.data.keyword) {
          count++;
        }
      }

      if (count == 0) {
        // 如果搜索到结果，再加入历史搜索
        if (that.data.keyword && !res.responseBody.isRecommend ) {
          searchData.push(that.data.keyword);
          if (searchData.length>=10){
            searchData.shift()
          }
          wxcache.put('searchData', searchData.reverse());
        }
      }

      app.globalData.searchGoodInfo = res.responseBody
      that.setData({
        historyKeyword: searchData,
        searchStatus: true
      })
      
      wx.redirectTo({
        url: '../catalog/catalog?type=SEARCH&keyword=' + that.data.keyword
      }); 
      
    })
  },

  inputChange: function (e) {
    this.data.keyword = e.detail.value;
    this.data.searchStatus = false;
  },

  inputFocus: function () {
    this.setData({
      searchStatus: false,
    });
  },

  clearHistory: function () {
    this.setData({
      historyKeyword: [],
      searchStatus: false,
    })
    wxcache.put('searchData', []);
  }, 

  /**
   * 点击关键词事件
  */
  onKeywordTap: function (event) {
    let keywordstr = event.target.dataset.keyword
    this.data.keyword = keywordstr
    this.searchByCondition()
  },
 
  /**
   * 键盘回车事件
  */
  onKeywordConfirm(event) {
    let keywordstr = event.detail.value
    this.data.keyword = keywordstr
    this.searchByCondition()
  },

  /*
  * 获取热搜数据
  */
  getHotKeyword: function() {
    var that = this;
    util.request(api.HotSearch).then(function (res) {
      if ('200' == res.code) {
        that.setData({
          hotKeyword: res.responseBody
        });
      }
    });
  }
});